package org.sakai.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.sakai.entity.*;
import org.sakai.service.MinioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "minio api操作")
@Controller
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioService minioService;
    @Operation(description = "列举路径下的所有文件")
    @GetMapping("/listFiles")
    public ApiResponseEntity<Object> listFiles(){
        return null;
    }

    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 生成唯一的文件ID
            String fileId = java.util.UUID.randomUUID().toString();
            String fileName = fileId + getFileExtension(file.getOriginalFilename());

            // 上传到MinIO
            Result<Image> result = minioService.upload("big-data-health", "images/" + fileName, file);

            if (result.isSuccess()) {
                // 返回前端期望的Image格式
                Map<String, String> imageResult = new HashMap<>();
                imageResult.put("id", fileId);
                imageResult.put("url", "/images/" + fileName);

                return ResponseEntity.ok(imageResult);
            } else {
                return ResponseEntity.status(500).build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName != null && fileName.lastIndexOf(".") > 0) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return ".jpg"; // 默认扩展名
    }


    // 提取相对路径（根据前端上传的绝对路径生成）
    private String extractRelativePath(String fullPath) {
        // 实现你的路径解析逻辑
        return fullPath; // 示例简化，实际应根据 prefix 或 base dir 截取路径
    }


}
